import { create } from "zustand";
import { persist } from "zustand/middleware";
import { loginApi, updatePwdApi, refreshTokenApi, getNewVersionApi } from "@/api/auth";
import { IUser } from "@/types/auth";
import { getTokenExpiration, getVersion } from "@/utils/utils";
import { LOCAL_KEY } from "@/constant/env";
import { Toast } from "antd-mobile";
import { useChatStore } from "./app";
import Router from "next/router";

export const AUTH_KEY = LOCAL_KEY + "__auth";
interface AuthState {
  token: string;
  tokenExpiration: number,
  user: IUser;
  version: string,
  setToken: (token: string) => void;
  isAuthed: () => boolean;
  clearAuth: () => void;
  refreshToken: () => Promise<void>;
  changePwd: (query: any) => Promise<void>;
  login: (query: any) => Promise<void>;
  getNewVersion: () => Promise<void>;
}

export const useAuthStore = create(
  persist<AuthState>(
    (set, get) => ({
      token: "",
      tokenExpiration: getTokenExpiration(),
      user: {
        id: "",
        userForApp: "",
        username: "",
        url: "",
        appUser: null,
      },
      version: "",
      setToken: (token) => {
        set({ token });
      },
      isAuthed: () => get().token !== "",
      clearAuth: () => {
        set({
          token: "",
          user: {
            id: "",
            userForApp: "",
            username: "",
            url: "",
            appUser: null,
          },
          tokenExpiration: getTokenExpiration(),
        });
      },
      getNewVersion: async () => {
        const response = await getNewVersionApi();
        set({
          version: response.versionNum
        })
      },
      refreshToken: async () => {
        try {
          const response = await refreshTokenApi();
          set({
            token: response.token,
            tokenExpiration: getTokenExpiration()
          });
        } catch (error) {
          set({
            tokenExpiration: getTokenExpiration()
          });
        }
      },
      login: async (query) => {
        const appStore = useChatStore.getState();
        const response = await loginApi(query);
        set({
          token: response.token,
          tokenExpiration: getTokenExpiration(),
          user: response.user,
        });
        response.user.url && appStore.updateAvatar(response.user.url)
        get().getNewVersion()
      },
      changePwd: async (query) => {
        await updatePwdApi({
          ...query,
          id: get().user.id
        });
        Toast.show({
          icon: "success",
          content: "修改成功",
        });
        get().clearAuth();
        Router.replace("/login");
      },
    }),
    {
      name: AUTH_KEY,
      version: getVersion(),
    },
  ),
);
